package 其他.华为;


import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


public class 岛屿打通连通水 {
    int[][] g;
    int[][] vis;
    int n, m;
    public static void main(String[] args) {

//        System.out.println(daoyu(G));



        Scanner scanner = new Scanner(System.in);
        String s1 = scanner.nextLine();
        岛屿打通连通水 main = new 岛屿打通连通水();
        main.n = Integer.parseInt(s1);
        String s2 = scanner.nextLine();
        main.m = Integer.parseInt(s2);
        if(main.n==0 || main.m==0){
            System.out.println(0);
            return;
        }


        int[][] G = new int[main.n][main.m];
        for (int i = 0; i < G.length; i++) {
            String row = scanner.nextLine();
            String[] s = row.split(" ");
            int j=0;
            for (String s3 : s) {
                G[i][j++]=Integer.parseInt(s3);
            }
        }

        System.out.println(main.daoyu(G));
    }



    public int daoyu(int[][] grid) {
        g=grid;
        n=g.length; m=g[0].length;
        vis = new int[g.length][g[0].length];
        int count =0;
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < g.length; i++) {
            for (int j = 0; j < g[0].length; j++) {
                if(g[i][j] == 1 || g[i][j]==2){
                    two=0;
                    int x=i,y=j;
                    pre(x,y);
                    if(g.length==1||g[0].length==1){
                        count += 2*two;
                        return count;
                    }
                    if(two>=1){
                        count++;
                    }
                    count++;
                }
            }
        }
        return count;
    }

    int two=0;
    int[][] fx = {
            {-1,1},
            {1,1},
            {-1,-1},
            {1,-1},
            {-1,0},
            {1,0},
            {0,-1},
            {0,1}
    };
    private void pre(int i, int j) {
        vis[i][j] = 1;
        if(g[i][j]==2){
            two++;
        }
        g[i][j]=0;
        for (int k = 0; k < fx.length; k++) {
            int x = i+fx[k][0], y = j+fx[k][1];
            if(x<0 || x>=n || y<0 || y>=m || g[x][y]==0|| vis[x][y]==1) {
                continue;
            }
            pre(x, y);
        }
    }
}
